package cn.itsource.xhy.basic.service.impl;

import cn.itsource.xhy.basic.service.ICodeService;
import cn.itsource.xhy.user.contants.UserContants;
import cn.itsource.xhy.user.domain.User;
import cn.itsource.xhy.user.mapper.UserMapper;
import cn.itsource.xhy.utils.SendMsgUtis;
import cn.itsource.xhy.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void sendCode(Map<String, String> map) {
        // 生成一个六位数的随机数验证码
        String code = StrUtils.getRandomString(6);
        // 拿到传过来的手机号
        String phone = map.get("phone");
        if (UserContants.REGISTER_CODE.equals(map.get("codeType"))){
            // 通过电话查对象
            User user = userMapper.findByPhone(phone);
            // 判断对象是否存在
            if(user!=null){
                throw new RuntimeException("该手机号已被注册，请直接登录");
            }
        }

        // 60秒中不能重复点击
        // 拿到验证码
        String codeAndTime = (String)redisTemplate.opsForValue().get(map.get("codeType")+":"+phone);
        // 判断是否存再验证码
        if(codeAndTime!=null){
            // 拿到时间错
            Long time = Long.valueOf(codeAndTime.split(":")[1]);
            // 判断是否在一分钟之类
            if(System.currentTimeMillis()-time<60*1000){
                throw new RuntimeException("操作过于频繁");
            } else {
                // 如果在一分钟之外,拿到验证码
                code = codeAndTime.split(":")[0];
            }
        }

        // 将数据放在redis中
        redisTemplate.opsForValue().set(map.get("codeType")+":"+phone, code + ":"+ System.currentTimeMillis(), 5, TimeUnit.MINUTES);
        // 发送短信
        // SendMsgUtis.send(phone,"您的验证码为：" + code + "，5分钟有效");
        System.out.println(code);
    }
}
